/*** credits:
http://people.csail.mit.edu/dfhuynh/projects/timeline-exhibit/filtered-sources.js
***/

     Timeline.FilteredEventSource = function(baseEventSource, match) {
		    this._baseEventSource = baseEventSource;
		    this._match = match;
		    
		    this._events = new SimileAjax.EventIndex();
		    this._listeners = [];
		    
		    var self = this;
		    this._eventListener = {
		        onAddMany: function() { console.log("here"); self._onAddMany(); },
		        onClear:   function() { self._onClear(); }
		    }
		    this._baseEventSource.addListener(this._eventListener);
		    
		    if (this._baseEventSource.getCount() > 0) {
		        this._onAddMany();
		    }
		};
		
		Timeline.FilteredEventSource.prototype.addListener = function(listener) {
		    this._listeners.push(listener);
		};
		
		Timeline.FilteredEventSource.prototype.removeListener = function(listener) {
		    for (var i = 0; i < this._listeners.length; i++) {
		        if (this._listeners[i] == listener) {
		            this._listeners.splice(i, 1);
		            break;
		        }
		    }
		};
		
		Timeline.FilteredEventSource.prototype.getEvent = function(id) {
		    return this._events.getEvent(id);
		};
		
		Timeline.FilteredEventSource.prototype.getEventIterator = function(startDate, endDate) {
		    return this._events.getIterator(startDate, endDate);
		};
		
		Timeline.FilteredEventSource.prototype.getEventReverseIterator = function(startDate, endDate) {
		    return this._events.getReverseIterator(startDate, endDate);
		};
		
		Timeline.FilteredEventSource.prototype.getAllEventIterator = function() {
		    return this._events.getAllIterator();
		};
		
		Timeline.FilteredEventSource.prototype.getCount = function() {
		    return this._events.getCount();
		};
		
		Timeline.FilteredEventSource.prototype.getEarliestDate = function() {
		    return this._events.getEarliestDate();
		};
		
		Timeline.FilteredEventSource.prototype.getLatestDate = function() {
		    return this._events.getLatestDate();
		};
		
		Timeline.FilteredEventSource.prototype._fire = function(handlerName, args) {
		    for (var i = 0; i < this._listeners.length; i++) {
		        var listener = this._listeners[i];
		        if (handlerName in listener) {
		            try {
		                listener[handlerName].apply(listener, args);
		            } catch (e) {
		                SimileAjax.Debug.exception(e);
		            }
		        }
		    }
		};
		
		Timeline.FilteredEventSource.prototype._onAddMany = function() {
		    this._events.removeAll();
		    
		    var i = this._baseEventSource.getAllEventIterator();
		    while (i.hasNext()) {
		        var evt = i.next();
		        if (this._match(evt)) {
		            this._events.add(evt);
		        }
		    }
		    
		    this._fire("onAddMany", []);
		};
		
		Timeline.FilteredEventSource.prototype._onClear = function() {
		    this._events.removeAll();
		    this._fire("onClear", []);
		};

